﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Admin.NET.Application.Util.Extension;
using Radius.NET.Interface.Kingdee.Entity;

namespace Radius.NET.Interface.Kingdee.Service.BasicInfoModule;


/// <summary>
/// 基础资料服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 002)]
public class StockService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Stock> stockRespository;

    private readonly KingdeeUtil _kingdeeUtil;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="_stockRespository"></param>
    /// <param name="kingdeeUtil"></param>
    public StockService(SqlSugarRepository<Stock> _stockRespository,
        KingdeeUtil kingdeeUtil)
    {
        stockRespository = _stockRespository;
        _kingdeeUtil = kingdeeUtil;
    }

    #region 同步金蝶云星空库位档案到本地
    /// <summary>
    /// 同步金蝶云星空库位档案到本地
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/basicinfo/stocklist/{cid}"), AllowAnonymous]
    public async Task<object> SyncStockList(int cid)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_basicinfo_stocklist");
        List<Stock> InserLsit = new();
        List<Stock> UpdateList = new();

        var list = KingdeeUtil.Query<BD_STOCK_Dto>(KingdeeFormConst.BD_STOCK, $"FUseOrgId.FNumber = '{KingdeeConfigConst.ORGID}'");

        if (list.Count == 0)
        {
            throw Oops.Oh("金蝶无数据可同步！");
        }
        //循环库位档案插入本地表
        foreach (var item in list)
        {
            Stock obj = new()
            {
                Stock_ID = item.FNumber,
                Description = item.FName,
                ParentID = item.FStockProperty,
                _cid = cid,
            };
            //判断库位档案是否存在
            if (!await stockRespository.IsAnyAsync(x => x.Stock_ID == obj.Stock_ID))
            {
                InserLsit.Add(obj);
            }
            else
            {
                UpdateList.Add(obj);
            }
        }
        if (InserLsit.Count == 0 && UpdateList.Count == 0)
        {
            throw Oops.Oh("当前同步的库位本系统中已存在！");
        }

        try
        {
            //stockRespository.Context.Ado.BeginTran();
            var obj = await stockRespository.AsInsertable(InserLsit).ExecuteCommandAsync();
            obj = await stockRespository.AsUpdateable(UpdateList).UpdateColumns(x => x.Description).ExecuteCommandAsync();
            //stockRespository.Context.Ado.CommitTran();
            return InserLsit.Concat(UpdateList);
        }
        catch (Exception ex)
        {
            //stockRespository.Context.Ado.RollbackTran();
            throw Oops.Oh(ex.Message);
        }
    }
    #endregion

}
